package org.ielts;

import static com.yifeng.struts2.ResultConstants.FILL;
import static com.yifeng.struts2.ResultParameters.setLocation;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.yifeng.ProfileContext;
import com.yifeng.actionlog.ActionLog;
import com.yifeng.actionlog.imsi.IImsiFilterService;
import com.yifeng.actionlog.imsi.Imsi;
import com.yifeng.actionlog.imsi.ImsiService;
import com.yifeng.actionlog.imsi.IspForbiddenResult;
import com.yifeng.actionlog.statistics.ActionLogService;
import com.yifeng.actionlog.token.ITokenService;
import com.yifeng.actionlog.token.Token;
import com.yifeng.actionlog.token.TokenResultUtils;
import com.yifeng.actionlog.token.TokenStatus;
import com.yifeng.profile.Profile;
import com.yifeng.security.authentication.Authentication;
import com.yifeng.security.authorization.Authorization;
import com.yifeng.sitemap.Catalog;
import com.yifeng.sitemap.Request;
import com.yifeng.sitemap.SiteMap;
import com.yifeng.web.IValidateProcess;
import com.yifeng.web.ValidateResult;

public class JspValidateProcess implements IValidateProcess {

	HashSet<String> skipUrls = new HashSet<String>();
	HashSet<String> loginUrls = new HashSet<String>();

	public JspValidateProcess() {
		// 不验证Token的路径
		loginUrls.add("/security/auth/login");
		loginUrls.add("/security/auth/logout");
	}

	@Autowired
	private Authentication authentication;

	@Autowired
	protected Authorization authorization;

	@Autowired
	SiteMap siteMap;

	@Autowired
	ITokenService tokenService;

	public boolean validate(ValidateResult validateResult) {
		Profile profile = Profile.getInstance();

		ActionLog actionLog = profile.getActionLog();

		Request request = SiteMap.findRequest();

		// 验证开关
		if (request == null) {
			return true;
		}
		String requestId = request.getId();

		if (!loginUrls.contains(requestId)) {
			// Token检查
			String tokenStr = tokenService.readToken(actionLog);
			Token token = tokenService.checkToken(tokenStr);
			if (token.getStatus() != TokenStatus.Correct) {
				TokenResultUtils.buildResult(token, actionLog, validateResult);
				return false;
			} else {
				if (tokenService.needReIssue(token)) {
					tokenService.reclaim(token);
					if (profile.isAuthenticated()) {
						authentication.login(profile.getUserId());
					}
				}
			}
		}

		String privilege = request.getPrivilege();

		if (StringUtils.isNotBlank(privilege) && !authorization.hasAuthorized(privilege)) {
			setLocation("/errorPages/noAuthenticated.jsp");
			validateResult.setResult(FILL);
			return false;
		}

		return true;
	}

	public void init() {

	}

	public void destroy() {

	}

}
